/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;

/**
 *
 * @author Lenovo
 */
public class NewClass {
 /**
     * 测试是否能够连接数据源<br>
     * 根据传入的数据源，测试是否能够正常连接
     * @param   dataSource 需要测试的数据源
     * @throws  Exception 如果测试除了异常，将异常抛出，由调用者根据是否是连接超时还是其他原因来具体处理
     * @return	boolean 测试结果
     * @author	Administrator
     * @since	PASIAM V1.0
     */
    public boolean testConnect(DataSource dataSource) throws Exception{
        
        // 声明一个返回值、数据库连接、查询对象、查询结果对象
        boolean connectResult = false;
        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        
        // 如果需要测试的数据源不为空则测试，否则抛出异常
        if(dataSource != null){
            try {
                //LogUtil.getDebugLogger().debug("测试数据库<" + current_key + ">连接开始");
                conn = dataSource.getConnection();
                statement = conn.prepareStatement("select count(1) from DEPARTMENT WHERE ID=?");
                statement.setInt(1, 1);
                rs = statement.executeQuery();
                //LogUtil.getDebugLogger().debug("测试数据库<" + current_key + ">连接成功");
                connectResult = true;
            }catch(Exception e){            
               // LogUtil.getDebugLogger().debug("测试数据库<" + current_key + ">连接失败");
                //LogUtil.saveRunLog(e);
                throw e;
            }finally{
                try {
                    if(null != rs){
                        rs.close();
                    }
                    if(null != statement){
                        statement.close();
                    }
                    if(null != conn && !conn.isClosed()){                    
                        conn.close();
                        conn = null;
                        //LogUtil.getDebugLogger().debug("测试数据库<" + current_key + ">连接关闭成功");
                    }
                } catch (SQLException e) {
                    //LogUtil.getDebugLogger().debug("测试数据库<" + current_key + ">连接关闭失败");
                }
            }
        }else{
           // LogUtil.getDebugLogger().debug("测试数据库<" + current_key + ">为空");            
            throw new Exception("测试的数据源为空");
        }          
        return connectResult;
    }    
}
